package com.imageim.yimirror.ui.fragment;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.imageim.yimirror.R;
import com.imageim.yimirror.base.BaseFragment;
import com.imageim.yimirror.base.Constants;
import com.imageim.yimirror.bean.DailyRecommendBean;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.ui.dialog.PromptDialog;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.net.NetPresenterImpl;
import com.imageim.yimirror.net.NetView;
import com.imageim.yimirror.ui.adapter.DailyRecommendAdapter;
import com.imageim.yimirror.ui.widght.EmptyView;
import com.imageim.yimirror.ui.widght.LoadingView;
import com.martin.ads.omoshiroilib.util.BitmapUtils;
import com.yarolegovich.discretescrollview.DiscreteScrollView;
import com.yarolegovich.discretescrollview.transform.ScaleTransformer;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

import butterknife.BindView;

/**
 * Created by Yuaihen.
 * on 2018/7/6
 * 今日推荐界面Fragment  ->为您推荐界面
 */
public class RecommendForYouFragment extends BaseFragment implements NetView {

    @BindView(R.id.scrollView)
    DiscreteScrollView mScrollView;
    @BindView(R.id.empty_view)
    EmptyView mEmptyView;
    @BindView(R.id.loading_view)
    LoadingView mLoadingView;
    private DailyRecommendAdapter mAdapter;
    private NetPresenterImpl mNetPresenter;
    private List<DailyRecommendBean.ClothingsBean> mClothingsBeanList;
    private PromptDialog mDialog;
    private ImageView mIvBigQrcode;
    private String mQrCodeUrl;
    private HashMap<String, String> mCollectMap;
    private HashMap<String, String> mCancelCollectMap;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_recommend_for_you;
    }


    @Override
    protected void initListener() {
        mAdapter = new DailyRecommendAdapter(mContext, mClothingsBeanList);
        mScrollView.setItemTransformer(new ScaleTransformer());
        mScrollView.setAdapter(mAdapter);
        mAdapter.setOnItemOnclickListener(new DailyRecommendAdapter.OnItemOnclickListener() {
            @Override
            public void onClickShare(int position) {
                //点击分享
                openBigQrCode(position);
            }

            @Override
            public void onClickLike(int position, boolean collect) {
                //添加或者取消收藏
                likeOrCancel(position, collect);
            }
        });


        mEmptyView.setOnFinishBtnClickListener(new EmptyView.OnFinishBtnClickListener() {
            @Override
            public void onFinishBtnClick() {
                getDailyClothing();
            }
        });
    }

    @Override
    protected void initData() {
        mNetPresenter = new NetPresenterImpl(this);
        getDailyClothing();
    }


    private static final int MSG_GET_DAILY_RECOMMEND = 0x0001;
    private static final int MSG_ADD_COLLECT = 0x002;
    private static final int MSG_CANCEL_COLLECT = 0x003;

    /**
     * 获取今日推荐照片
     */
    private void getDailyClothing() {
        HashMap<String, String> map = new HashMap<>(1);
        map.put(Constants.PHOTO_NO, UserUtil.getPhotoNo());

        //temp
        //        map.put(Constants.PHOTO_NO, "CN201812042048016FYT");
        //        map.put(Constants.TOKEN, "00d9b360f856435685c1187bbfd826041543927657615");
        mNetPresenter.getObject(mContext, NetConstants.URL.GET_DAILY_RECOMMEND, map, DailyRecommendBean.class, MSG_GET_DAILY_RECOMMEND);
    }

    /**
     * 添加收藏
     *
     * @param clothingCode 服装编码
     */
    private void addCollect(String clothingCode) {
        if (mCollectMap == null) {
            mCollectMap = new HashMap<>(4);
        }
        mCollectMap.put(Constants.USER_ID, UserUtil.getUserId());
        mCollectMap.put(Constants.CLOTHING_CODE, clothingCode);

        //temp
        //        mCollectMap.put("token", "00d9b360f856435685c1187bbfd826041543927657615");
        //        mCollectMap.put("userId", "BC20181029101458A0pT");
        mNetPresenter.getObject(mContext, NetConstants.URL.COLLECT_CLOTHING, mCollectMap, MSG_ADD_COLLECT);
    }


    /**
     * 取消收藏
     *
     * @param clothingCode 服装编码
     */
    private void cancelCollect(String clothingCode) {
        if (mCancelCollectMap == null) {
            mCancelCollectMap = new HashMap<>(4);
        }
        mCancelCollectMap.put(Constants.USER_ID, UserUtil.getUserId());
        mCancelCollectMap.put(Constants.CLOTHING_CODE, clothingCode);

        //temp
        //        mCancelCollectMap.put("token", "00d9b360f856435685c1187bbfd826041543927657615");
        //        mCancelCollectMap.put("userId", "BC20181029101458A0pT");
        mNetPresenter.getObject(mContext, NetConstants.URL.CANCEL_COLLECT, mCancelCollectMap, MSG_CANCEL_COLLECT);
    }


    /**
     * 点击二维码弹开的Dialog
     */
    private void openBigQrCode(int position) {
        if (mClothingsBeanList != null && mClothingsBeanList.size() > 0) {
            mQrCodeUrl = mClothingsBeanList.get(position).getQrcode();

            if (!TextUtils.isEmpty(mQrCodeUrl)) {
                if (mDialog == null) {
                    mDialog = new PromptDialog(mContext);
                    mDialog.setOutsideCanelable(true);
                    mDialog.bindView(R.layout.dialog_big_qrcode, new PromptDialog.BindViewListener() {
                        @Override
                        public void onBindView(View contentView) {
                            mIvBigQrcode = contentView.findViewById(R.id.iv_bigQrCode);
                            mIvBigQrcode.setImageBitmap(BitmapUtils.getQrcodeBitmapWithPadding(mQrCodeUrl, 300, Color.BLACK, 5));
                        }
                    }).show();
                } else {
                    mIvBigQrcode.setImageBitmap(BitmapUtils.getQrcodeBitmapWithPadding(mQrCodeUrl, 300, Color.BLACK, 5));
                    mDialog.show();
                }
            }
        }

    }


    @Override
    public void onLoadPre(int msgCode) {
        if (msgCode == MSG_GET_DAILY_RECOMMEND) {
            showLoading();
            hideEmptyView();
        }
    }

    @Override
    public void onLoadSuccess(Object result, int msgCode) {
        if (msgCode == MSG_GET_DAILY_RECOMMEND) {
            hideLoading();
            setAdapter(result);
        } else if (msgCode == MSG_ADD_COLLECT || msgCode == MSG_CANCEL_COLLECT) {
            updateCollect();
        }
    }


    @Override
    public void onLoadFail(int errorCode, String errorMsg, int msgCode) {
        if (msgCode == MSG_GET_DAILY_RECOMMEND) {
            hideLoading();
            showEmptyView(true);
        }

        toast(errorCode + errorMsg);
    }

    /**
     * 设置Adapter数据
     *
     * @param result 返回的数据集合
     */
    private void setAdapter(Object result) {
        if (result != null) {
            DailyRecommendBean bean = (DailyRecommendBean) result;
            mClothingsBeanList = Optional.ofNullable(bean.getClothings())
                    .orElse(new ArrayList<>());

            if (mClothingsBeanList.size() > 0) {
                mAdapter.setData(mClothingsBeanList);
            } else {
                showEmptyView(false);
            }
        } else {
            showEmptyView(false);
        }
    }

    /**
     * 收藏和取消收藏
     */
    private void likeOrCancel(int position, boolean collect) {
        if (mClothingsBeanList == null || mClothingsBeanList.size() <= 0) {
            return;
        }

        String clothingCode = mClothingsBeanList.get(position).getClothingCode();
        if (!TextUtils.isEmpty(clothingCode)) {
            if (collect) {
                //没有收藏  添加收藏
                addCollect(clothingCode);
            } else {
                //已经收藏  取消收藏
                cancelCollect(clothingCode);
            }
        }
    }


    /**
     * 显示空布局
     *
     * @param isError 是网络错误还是数据为空
     */
    private void showEmptyView(boolean isError) {
        if (mEmptyView != null) {
            mEmptyView.setVisibility(View.VISIBLE);
            //网络错误显示刷新按钮
            if (isError) {
                mEmptyView.setErrorImg(R.drawable.ic_error);
                mEmptyView.setErrorContent("数据获取失败，请重试~");
                mEmptyView.setBtnVisiable(true);
            } else {
                mEmptyView.setErrorImg(R.drawable.ic_no_result);
                mEmptyView.setErrorContent("暂无服装数据~");
                mEmptyView.setBtnVisiable(false);
            }
        }
    }

    private void hideEmptyView() {
        if (mEmptyView != null) {
            mEmptyView.setVisibility(View.GONE);
        }
    }

    private void showLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.VISIBLE);
        }
    }

    private void hideLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onEventMainThread(EventMessage event) {
        super.onEventMainThread(event);
        if (event.getCode() == EventCode.CODE_REFRESH_ADAPTER) {
            String clothingCode = (String) event.getValue();
            updateSelectState(clothingCode);
        }
    }

    /**
     * 我的收藏删除之后刷新选中状态
     *
     * @param clothingCode
     */
    private void updateSelectState(String clothingCode) {
        if (mClothingsBeanList == null || mClothingsBeanList.size() <= 0) {
            return;
        }

        for (int i = 0; i < mClothingsBeanList.size(); i++) {
            if (clothingCode.equals(mClothingsBeanList.get(i).getClothingCode())) {
                mClothingsBeanList.get(i).setCollectFlag(0);
                break;
            }
        }
        mAdapter.setData(mClothingsBeanList);
        mAdapter.notifyDataSetChanged();
    }

    private void updateCollect() {
        EventBus.getDefault().post(new EventMessage(EventCode.CODE_REFRESH_WITH_COLLECT_PAGE, null));
    }

}
